﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Web;
using System.Web.Mvc;

namespace FacialClub.Helpers
{
    /// <summary>
    /// Gravatar Helpers
    /// </summary>
    public static class GravatarHelpers
    {
        /// <summary>
        /// Gravatar
        /// </summary>
        /// <param name="helper"></param>
        /// <param name="email"></param>
        /// <param name="size"></param>
        /// <returns></returns>
        public static string Gravatar(this HtmlHelper helper, string email, int size)
        {
            const string result = "<img src=\"{0}\" alt=\"Gravatar\" class=\"gravatar\" />";
            var url = getGravatarUrl(email, size);
            return string.Format(result, url);
        }

        static string getGravatarUrl(string email, int size)
        {
            return (string.Format("http://www.gravatar.com/avatar/{0}?s={1}&r=PG",
                        encryptMd5(email), size.ToString()));
        }

        static string getGravatarUrl(string email, int size, string defaultImagePath)
        {
            return getGravatarUrl(email, size) + string.Format("&default={0}",
                       defaultImagePath);
        }

        static string encryptMd5(string value)
        {
            var md5 = new MD5CryptoServiceProvider();
            var valueArray = System.Text.Encoding.ASCII.GetBytes(value);
            valueArray = md5.ComputeHash(valueArray);
            var encrypted = "";
            for (var i = 0; i < valueArray.Length; i++)
                encrypted += valueArray[i].ToString("x2").ToLower();
            return encrypted;
        }
    }
}